// @ts-ignore
import { OffscreenSprite, MP4Clip, Combinator } from "../../@webav/av-cliper/dist/av-cliper.js";
import { getBolbUrl } from "./tool";
import type sprType from "../type/spr.d";

async function loadSprite(clip: any, name?: string): Promise<sprType> {
  name || (name = "spr" + Math.random());
  return new Promise(async (resolve) => {
    let TEMP: sprType["spr"] = new OffscreenSprite(
      name!,
      clip
    ) as unknown as sprType["spr"];
    TEMP.reLoad = async () =>
      new OffscreenSprite(name!, await clip.reGetClip());
    resolve(TEMP);
  });
}

async function getMP4Clip(url: string) {
  let TEMP: MP4Clip & { reGetClip?: Function } = new MP4Clip(
    (await fetch(url)).body!
  );
  TEMP.reGetClip = async () => new MP4Clip((await fetch(url)).body!);
  return TEMP;
}

async function getMP4ClipFromFile(file: File) {
  return getMP4Clip(await getBolbUrl(file));
}

function getReturnUrl(com: Combinator): Promise<string> {
  return new Promise((resolve) => {
    new Response(com.output()).blob().then((src) => {
      resolve(URL.createObjectURL(src));
    });
  });
  // 下面是通过拼接Uint8Array实现输出，以后比对一下效率
  // let out = com.output().getReader();
  // let sum = 0;
  // let data: Array<Uint8Array> = [];
  // return new Promise((resolve) => {
  //   function getData() {
  //     out.read().then(({ done, value }) => {
  //       if (done) {
  //         let newArray = new Uint8Array();
  //         for (let k = 0; k < data.length; k++) {
  //           newArray = concat(newArray, data[k]);
  //         }
  //         // console.log(newArray)
  //         out.cancel();
  //         resolve(URL.createObjectURL(new Blob([newArray])));
  //         return;
  //       }
  //       sum += value.length;
  //       console.log(sum);
  //       data.push(value);
  //       getData();
  //     });

  //     function concat(array1: Uint8Array, array2: Uint8Array) {
  //       let mergedArray = new Uint8Array(array1.length + array2.length);
  //       mergedArray.set(array1, 0);
  //       mergedArray.set(array2, array1.length);
  //       return mergedArray;
  //     }
  //   }
  //   getData();
  // });
}

export { loadSprite, getReturnUrl, getMP4Clip, getMP4ClipFromFile };
